<template>
	<view class="page-content">
		<default-navbar :pageTitle="formData.projectId ? '编辑项目' : '新增项目'"></default-navbar>
		<view class="page-main">
			<!--  errorType="toast" -->
			<up-form labelPosition="top" :model="formData" ref="formRef" labelWidth='300'
				:labelStyle="{ 'padding-left': '20rpx', 'font-weight': 'bold' }">
				<view class="projectInformation">
					<view class="title">
						<i class="iconfont icon-a-pinghangsibianxing2 red"></i>
						<view class="text">
							项目信息
						</view>
						<i class="iconfont icon-a-pinghangsibianxing2 blue"></i>
					</view>
					<view class="main">
						<up-form-item label="项目名称" prop="projectName" required>
							<up-input placeholder="请输入项目名称" v-model="formData.projectName"></up-input>
						</up-form-item>
						<up-form-item label="客户名称" prop="enterpriseId" required>
							<uni-data-select :clear="true" style="width: 100%;" placeholder="请选择客户"
								v-model="formData.enterpriseId" :localdata="userList_data"
								@change="changeEnterprise"></uni-data-select>
						</up-form-item>
						<up-form-item label="联系人姓名" prop="contactName" required>
							<up-input placeholder="请输入联系人姓名" v-model="formData.contactName"></up-input>
						</up-form-item>
						<up-form-item label="联系人职务" prop="contactTitle" required>
							<up-input placeholder="请输入联系人职务" v-model="formData.contactTitle"></up-input>
							<!-- <uni-data-select :clear="true" style="width: 100%;" placeholder="请选择联系人职务"
								v-model="formData.contactTitle" :localdata="contactTitleList_data"></uni-data-select> -->
						</up-form-item>
						<up-form-item label="联系方式" prop="contactInformation" required>
							<up-input placeholder="请输入联系方式" v-model="formData.contactInformation"></up-input>
						</up-form-item>
						<up-form-item label="首次接触日期" prop="firstContactDate" required>
							<view style="width: 100%;" @click="showFirstContactDate">
								<up-input readonly placeholder="请选择日期" v-model="formData.firstContactDate">
									<template v-slot:suffix>
										<view
											style="display: flex;flex-direction: row;align-items: center;justify-content: flex-start;">
											<up-icon name="calendar" size="24"></up-icon>
										</view>
									</template>
								</up-input>
							</view>
						</up-form-item>
					</view>
				</view>
				<view class="projectInformation">
					<view class="title">
						<i class="iconfont icon-a-pinghangsibianxing2 red"></i>
						<view class="text">
							我方团队信息
						</view>
						<i class="iconfont icon-a-pinghangsibianxing2 blue"></i>
					</view>
					<view class="main">
						<up-form-item label="对接公司" prop="deptId" required>
							<uni-data-select :clear="true" style="width: 100%;" placeholder="请选择对接公司"
								v-model="formData.deptId" :localdata="deptList_data" @change="chooseCompany"></uni-data-select>
						</up-form-item>
						<up-form-item label="负责人" prop="chargeName" required style="width: 100%;">
							<view class="zlcBox" style="width: 100%;">
								<picker-select height="20px" width="100%" :showClose="true"
									placeholder="请选择负责人" valueName="nickName" keyName="nickName" :list="teamInfo_data"
									v-model="formData.chargeName"></picker-select>
							</view>
							
						</up-form-item>
						<up-form-item label="团队成员" prop="teamInfo" required>
							<view class="zlcBox" style="width: 100%;">
								<picker-select height="20px" width="100%" :showClose="true"
									multiple placeholder="请选择团队成员" valueName="nickName" keyName="nickName"
									:list="teamInfo_data" v-model="teamInfoComputed"></picker-select>
							</view>
						</up-form-item>
					</view>
				</view>
			</up-form>


			<view class="operateRroup" v-if="!formData.projectId">
				<view class="confirm-addVisitItem operateBtn">
					<up-button text="继续添加拜访记录" iconColor="#fff" @click="confirmHandle('linktoAddVisit')"></up-button>
				</view>
				<view class="confirm operateBtn">
					<up-button type="primary" text="完成并提交" color="#393e97"
						@click="confirmHandle('linktoDetailPage')"></up-button>
				</view>
			</view>
			<view class="operateRroup" v-else>
				<view class="confirm operateBtn">
					<up-button type="primary" text="提交" color="#393e97"
						@click="confirmHandle('linktoDetailPage')"></up-button>
				</view>
				<view class="confirm-addVisitItem operateBtn" v-if="hasPermission('miniapp:project:delete')">
					<up-button type="error" text="删除" color="red"
						@click="deleteItem(deleteProjectItem, formData.projectId, delta)"></up-button>
				</view>
				
			</view>
		</view>
		<!-- 首次接触时间 -->
		<up-datetime-picker ref="startDatePicker" :closeOnClickOverlay="true" format="YYYY-MM-DD" placeholder="请选择日期"
			:show="firstContactDate_visible" @close="firstContactDate_visible = false"
			@cancel="firstContactDate_visible = false" @confirm="firstContactDate_confirm"
			v-model="firstContactDateComputed" :minDate="minDate()" :maxDate="maxDate()" mode="date">

		</up-datetime-picker>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, watch, computed } from "vue"
	import { onLoad, onShow } from "@dcloudio/uni-app";
	//组件
	import defaultNavbar from "@/components/defaultNavbar/index.vue";
	import pickerSelect from "@/components/pickerSelect/index.vue"
	import uniDataSelect from "@/uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue"
	import ruleButton from "@/components/ruleButton/index.vue"
	//接口
	import type { AddProjectParams } from "@/api/addProject/types"
	import { addProject } from "@/api/addProject/index"
	import { projectItem, deleteProjectItem } from "@/api/projectList/index"
	import { enterpriseItem } from "@/api/userList/index"
	//hooks
	import useViewModel from './hooks/useViewModel'
	import useAppHookds from "@/appHooks/useViewModel"
	import useDataList from "@/appHooks/useDataList"
	const {
		minDate,
		maxDate,
		rules,
		firstContactDate_visible,
		firstContactDate_confirm,
		showFirstContactDate,
		delta
	} = useViewModel()


	let {
		getDeptList,
		deptList_data,
		getTeamInfo,
		teamInfo_data,
		getContactTitleList,
		contactTitleList_data,
		deleteItem,
		hasPermission
	} = useAppHookds()

	let {
		getUserList,
		userList_data
	} = useDataList()
	
	
	let formRef = ref(null) //form表单
	let startDatePicker = ref() //时间选择器ref
	//时间选择器回显
	let firstContactDateComputed = computed({
		get() {
			let { firstContactDate } = formData.value
			if (!firstContactDate) {
				return new Date().getTime()
			} else {
				return new Date(firstContactDate).getTime()
			}
		},
		set(val) {
			const ts = val < 1e12 ? val * 1000 : val;
			const date = new Date(ts);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			formData.value.firstContactDate = `${year}-${month}-${day}`
		}
	})


	//表单数据
	let formData = ref<AddProjectParams>({
		projectName: '',
		enterpriseId: '',
		contactName: '',
		contactTitle: '',
		contactInformation: '',
		firstContactDate: '',
		deptId: '',
		deptName: '',
		chargeName: '',
		teamInfo: '',
	})
	//团队成员回显
	let teamInfoComputed = computed({
		get() {
			let target = formData.value.teamInfo as string
			let result = target.split(',').filter(Boolean).map(item => {
				return { nickName: item }
			})
			return result
		},
		set(e : any) {
			if (!e) {
				formData.value.teamInfo = ""
			} else {
				formData.value.teamInfo = e.map(item => item.nickName).filter(Boolean).join()
			}
		}
	})

	//提交表单
	let addProjectHandle = (type ?: string) : Promise<void> => {
		return new Promise((resolve, reject) => {
			addProject(formData.value).then(res => {
				let { code, projectId } = res as any
				if (code == 200) {
					uni.showToast({
						title: '提交成功!'
					})
					setTimeout(() => {
						let { projectId: formId, enterpriseId, backPage } = formData.value
						if (type == 'linktoDetailPage') {
							if (formId) {
								uni.navigateBack()
							} else {
								if(backPage == 'userItemDetail'){
									uni.navigateBack()
								}else{
									uni.redirectTo({
										url: `/pages/projectItemDetail/projectItemDetail?projectId=${projectId}`
									})
								}
								
							}
						} else {
							uni.redirectTo({
								url: `/pages/addVisit/index?projectId=${projectId}`
							})
						}


					}, 1000)

					resolve()
				} else {
					reject()
				}
			}).catch(() => {
				reject()
			})
		})

	}

	//提交表单
	let confirmHandle = (type : string) : void => {
		formRef.value.validate().then(valid => {
			if (valid) {
				addProjectHandle(type)
			} else {
			}
		}).catch((err) => {
			// 处理验证错误  
			let [target] = err
			if (target) {
				uni.showToast({
					title: target.message,
					icon: 'none'
				})
			}
		});
	}

	//获取详情
	let getProjectItem = (projectId : string) : Promise<void> => {
		return new Promise((resolve, reject) => {
			projectItem(projectId).then(res => {
				let { data } = res as any
				data.deptId = String(data.deptId)
				formData.value = data
				resolve()
			}).catch((err) => {
				reject(err)
			})
		})
		
	}

	//先获取对接公司，再获取团队成员
	watch(() => formData.value.deptId, (newValue, oldValue) => {
		if (newValue) {
			getTeamInfo(newValue)
		}
	})

	//选择客户-回显其他信息
	let changeEnterprise = (e : string) : void => {
		getEnterpriseItem(e)
	}
	
	//选择对接公司
	let chooseCompany = (e: string) => {
		formData.value.teamInfo = ""
		formData.value.chargeName = ""
		formData.value = JSON.parse(JSON.stringify(formData.value))
		let target = deptList_data.value.find(item => item.deptId == e)
		if(target){
			formData.value.deptName = target.deptName
		}
		
	}

	//客户详情
	let getEnterpriseItem = (enterpriseId : string) : void => {
		enterpriseItem(enterpriseId).then((res : any) => {
			let { contactName, contactTitle, contactInformation } = res.data || {}
			formData.value.contactName = contactName
			formData.value.contactTitle = contactTitle
			formData.value.contactInformation = contactInformation
		})
	}

	//获取详情 - 编辑的场景
	onLoad((e) => {
		let { projectId, enterpriseId, backPage, backDelta } = e as any
		if (projectId && enterpriseId) {
			getProjectItem(projectId).then(() => {
				formData.value.enterpriseId = enterpriseId
				getEnterpriseItem(enterpriseId)
			})
		}else if(projectId && !enterpriseId){
			getProjectItem(projectId)
		}else if(!projectId && enterpriseId){
			formData.value.enterpriseId = enterpriseId
			getEnterpriseItem(enterpriseId)
		}
		
		if(backDelta){
			delta.value = Number(backDelta)
		}else{
			delta.value = 2
		}
		
		
		if(backPage){
			formData.value.backPage = backPage
		}
	})
	onShow(() => {
		getUserList()
	})
	onMounted(() => {
		formRef.value.setRules(rules)
		getContactTitleList()
		getDeptList()
		startDatePicker.value.innerValue = new Date().getTime();
	})
</script>

<script lang="ts">
	export default {
		options: {
			styleIsolation: 'shared',
		}
	}
</script>

<style lang="scss" scoped>
	.page-content {
		width: 100%;
		height: 100%;
		background: rgb(246, 246, 248);

		.page-main {
			display: block;
			flex: 1;
			width: 100%;
			padding: 20rpx;
			box-sizing: border-box;

			.projectInformation {
				background: #fff;
				border-radius: 6rpx;
				box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
				margin-bottom: 20rpx;
			}

			.operateRroup {
				margin: 40rpx;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-around;

				.operateBtn {
					flex: 1;
					padding: 0 20rpx;
					box-sizing: border-box;
				}
			}

			.title {
				text-align: center;
				font-weight: bold;
				padding: 30rpx 0;
				border-bottom: 2rpx solid rgba(235, 235, 237, 0.5);
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				.red {
					color: #ec2f8a;
				}

				.blue {
					color: #364094;
				}

				.text {
					margin: 0 20rpx;
				}
			}

			.main {
				padding: 20rpx;
				box-sizing: border-box;
			}
		}



		::v-deep .u-form-item__body__left__content__required {
			left: 0;
		}
	}
</style>